package com.alex.controller;

import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import cn.hutool.http.HttpUtil;
import com.alex.common.beans.ResultBean;
import com.alex.database_sql.entity.BasicJourMerge;
import com.alex.database_sql.entity.EarlyWarningJournal;
import com.alex.database_sql.entity.JidCitationSort;
import com.alex.database_sql.entity.PublicationDataSelect;
import com.alex.database_sql.mapper.BasicJourMergeMapper;
import com.alex.database_sql.mapper.EarlyWarningJournalMapper;
import com.alex.database_sql.mapper.JidCitationSortMapper;
import com.alex.database_sql.mapper.PublicationDataSelectMapper;
import com.alex.entityVo.Cn_detail_01;
import com.alex.entityVo.JourSearchVo;
import com.alex.sevice.StaticService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.google.gson.Gson;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.sql.SQLException;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;


@RequestMapping("/search_v2")
@RestController
@SuppressWarnings("ALL")
@Tag(name = "期刊推荐")
public class JourSelectController {

    @Autowired
    private PublicationDataSelectMapper publicationDataSelectMapper;
    @Autowired
    private EarlyWarningJournalMapper earlyWarningJournalMapper;
    @Autowired
    private JidCitationSortMapper jidCitationSortMapper;

    @Resource
    StaticService staticService;


    public static String RESTURL_ES = "http://10.1.1.11:29000";

    public static String BASE_TABLE = "basic_jour_merge";


    public String auth_net_work(String title) {
        Map<String, Object> map = new HashMap<>();
        map.put("title", title);
        return HttpUtil.post(RESTURL_ES + "/journal_select/journal_select", map);
    }

    /*
    SELECT *
    FROM basic_jour_merge
    WHERE id IN (11, 12, 10)
    ORDER BY FIELD(id, 11, 12, 10);
    * */
    @Operation(summary = "期刊推荐", description = "输入标题,摘要,关键词,来进行检索推荐出期刊")
    @PostMapping(value = "select")
    public ResultBean<Object> select(@RequestBody JourSearchVo searchVo) {
        System.out.println("第一");
        Map<Integer, Integer> select = SelectJournalTitle.select(searchVo.getTitle(), searchVo.getKeyword(), searchVo.getAbs());
        System.out.println("第二");
        List<Integer> keys = new ArrayList<>();
        select.forEach((k, v) -> {
            keys.add(k);
        });
        staticService.insStat(searchVo.getTitle(), "期刊推荐");
        staticService.insStat(searchVo.getKeyword(), "期刊推荐");
        staticService.insStat(searchVo.getAbs(), "期刊推荐");
        if (keys.isEmpty()) {
            return new ResultBean<>();
        }
        //尝试去es匹配标题,如果有的话,就把他的期刊放在第一个
        try {
            System.out.println("尝试去es匹配标题,如果有的话,就把他的期刊放在第一个");
            String jourId = auth_net_work(searchVo.getTitle());
            if (StringUtils.isNotEmpty(jourId)) {
                keys.add(0, Integer.valueOf(jourId));
            }
        } catch (Exception e) {
            e.printStackTrace(System.err);
        }

        LambdaQueryChainWrapper<PublicationDataSelect> queryChainWrapper = new LambdaQueryChainWrapper<>(publicationDataSelectMapper);


        //如果有中科院分区的筛选
        queryChainWrapper.eq(StringUtils.isNotEmpty(searchVo.getZky()), PublicationDataSelect::getDaLei, searchVo.getZky());

        //如果有影响因子的选择
        if (StringUtils.isNotEmpty(searchVo.getJif())) {
            String[] jif = searchVo.getJif().split("_");
            queryChainWrapper.ge(PublicationDataSelect::getJcrIf, jif[0]);
            queryChainWrapper.le(PublicationDataSelect::getJcrIf, jif[1]);
        }
        //排序
        if (null != searchVo.getShortFiled()) {
            //默认按照相关度排序
            if (searchVo.getShortFiled() == 1) {
                queryChainWrapper.orderByDesc(PublicationDataSelect::getId);
            }
            //以影响因子排序
            if (searchVo.getShortFiled() == 2) {
                if (searchVo.getShortOrder() == 1) {
                    queryChainWrapper.orderByAsc(PublicationDataSelect::getJcrIf);
                } else {
                    queryChainWrapper.orderByDesc(PublicationDataSelect::getJcrIf);
                }
            }
            //以年份排序
            if (searchVo.getShortFiled() == 3) {
                if (searchVo.getShortOrder() == 1) {
                    queryChainWrapper.orderByAsc(PublicationDataSelect::getPublicationStartYear);
                } else {
                    queryChainWrapper.orderByDesc(PublicationDataSelect::getPublicationStartYear);
                }
            }
        }

        /**
         * 期刊发行信息和期刊官网
         */
        queryChainWrapper.in(PublicationDataSelect::getJid, keys);
        List<PublicationDataSelect> list = queryChainWrapper.list();

        /**
         * 中国人发文信息
         */

        for (PublicationDataSelect publicationDataSelect : list) {
            try {
                /**
                 * 是否是预警期刊  这个是list  有值的时候才展示这两个按钮
                 */
                List<EarlyWarningJournal> earlyWarningJournal = new LambdaQueryChainWrapper<>(earlyWarningJournalMapper)
                        .select(
                                EarlyWarningJournal::getId,
                                EarlyWarningJournal::getPublishingUnit,//发布机构
                                EarlyWarningJournal::getWarningLevel,//预警级别
                                EarlyWarningJournal::getYearOfPublication,//发布年份
                                EarlyWarningJournal::getPublicationDate,//发布日期
                                EarlyWarningJournal::getSourceUrl,//来源URL
                                EarlyWarningJournal::getSubject//学科
                        )
                        .eq(EarlyWarningJournal::getJid, publicationDataSelect.getJid()).list();
                if (null != earlyWarningJournal) {
                    publicationDataSelect.setEarlyWarningJournal(earlyWarningJournal);
                }
            } catch (Exception e) {
                System.out.println("是否是预警期刊出错了");
                e.printStackTrace(System.err);
            }
        }

        if (list.size() > 30) {
            list = list.subList(0, 30);
        }
        for (PublicationDataSelect one : list) {
            String publicationLanguages = one.getPublicationLanguages();
            try {
                List<String> parseArray = JSONObject.parseArray(publicationLanguages, String.class);
                one.setPublicationLanguages(parseArray.get(0));
            } catch (Exception e) {
                one.setPublicationLanguages(null);
            }
        }
        return new ResultBean<>(list);
    }

    @GetMapping(value = "detail")
    public ResultBean<Object> detail(Integer id) {
        try {
            List<Entity> query = Db.use().query("select * from " + BASE_TABLE + " where id = ?", id);
            return new ResultBean<>(query.get(0));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 查看中国人发文信息
     *
     * @param id
     * @return
     */
    @GetMapping(value = "cn_detail")
    public ResultBean<Object> cn_detail(Integer id) {
        Gson gson = new Gson();
        try {
            List<Entity> query = Db.use().query("select * from publication_data_select where id = ?", id);
            if (query.isEmpty()) {
                return new ResultBean<>();
            }
            Entity entity = query.get(0);
            String citeInfo = entity.getStr("cite_info");
            List<Cn_detail_01> cnDetail01s = JSONObject.parseArray(citeInfo, Cn_detail_01.class);
            List<Cn_detail_01> collect = cnDetail01s.stream().sorted((o1, o2) -> o2.getYear() - o1.getYear()).collect(Collectors.toList());
            return new ResultBean<>(collect);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return new ResultBean<>();
    }

}
